package com.example.cdpbookstore.web.servlet;

import com.example.cdpbookstore.pojo.entity.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@WebServlet("/remove-from-cart")
public class RemoveFromCartServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        if (id != null) {
            List<CartItem> cart = (List<CartItem>) request.getSession().getAttribute("cart");
            if (cart != null) {
                for (CartItem item : cart) {
                    if (Objects.equals(item.getBook().getId(), Long.valueOf(id))) {
                        cart.remove(item);
                        break;
                    }
                }
            }
        }
        response.sendRedirect("shopping-cart.jsp");
    }

}
